package com.shop.cereshop.app.service.recommend.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shop.cereshop.app.async.RecommendAsyncService;
import com.shop.cereshop.app.dao.recommend.CereRecommendCommentDAO;
import com.shop.cereshop.app.dao.recommend.CereRecommendLikesDAO;
import com.shop.cereshop.app.page.recommend.RecommendPageVO;
import com.shop.cereshop.app.param.recommend.RecommendLikeDTO;
import com.shop.cereshop.app.param.recommend.RecommendLikesParam;
import com.shop.cereshop.app.service.recommend.CereRecommendLikesService;
import com.shop.cereshop.app.tencent.im.service.MsgService;
import com.shop.cereshop.app.utils.RedisUtil;
import com.shop.cereshop.commons.domain.common.Page;
import com.shop.cereshop.commons.domain.recommend.CereRecommendLikes;
import com.shop.cereshop.commons.enums.RedisEnum;
import com.shop.cereshop.commons.exception.CoBusinessException;
import com.shop.cereshop.commons.tencent.im.enums.notice.SysNoticeTargetTypeEnum;
import com.shop.cereshop.commons.tencent.im.enums.notice.SysNoticeTypeEnum;
import com.shop.cereshop.commons.utils.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

@Service
public class CereRecommendLikesServiceImpl implements CereRecommendLikesService {

    @Value("${time.format}")
    private String time;

    @Autowired
    private CereRecommendLikesDAO cereRecommendLikesDAO;

    @Autowired
    private RecommendAsyncService recommendAsyncService;

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private CereRecommendCommentDAO recommendCommentDAO;
    @Resource
    private MsgService msgService;


    @Override
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    public Integer like(RecommendLikesParam param) throws CoBusinessException {
        String currentTime = TimeUtils.yyMMddHHmmss();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("recommend_id", param.getRecommendId());
        queryWrapper.eq("user_id", param.getUserId());
        queryWrapper.eq("like_type", 1);

        CereRecommendLikes cereRecommendLikes = cereRecommendLikesDAO.selectOne(queryWrapper);
        int row;
        if (cereRecommendLikes != null) {
            row = cereRecommendLikesDAO.delete(queryWrapper);
            if (row > 0) {
                //异步更新动态表的点赞数
//                 recommendAsyncService.updateRecommendLikeCount(param.getRecommendId(), 1,1);
                redisUtil.decrementLike(RedisEnum.USER_LIKE_KEY.getKey(), String.valueOf(param.getRecommendId()));
                return row;
            } else {
                throw new CoBusinessException("取消点赞失败");
            }
        }

        CereRecommendLikes likes = new CereRecommendLikes();
        likes.setRecommendId(param.getRecommendId());
        likes.setUserId(param.getUserId());
        likes.setIsRead(0);
        likes.setLikeType(1);
        likes.setCreateTime(currentTime);
        row = cereRecommendLikesDAO.insert(likes);
        if (row > 0) {
            //异步更新动态表的点赞数
//            recommendAsyncService.updateRecommendLikeCount(param.getRecommendId(), 2,1);
            redisUtil.incrementLike(RedisEnum.USER_LIKE_KEY.getKey(), String.valueOf(param.getRecommendId()));
            return row;
        } else {
            throw new CoBusinessException("点赞失败");
        }
    }

    /**
     * 获取用户点赞的动态
     *
     * @param buyerUserId 用户id
     * @param param       分页参数
     * @return Page<RecommendPageVO>
     */
    @Override
    public Page<RecommendPageVO> getLikeRecommendPage(Long buyerUserId, RecommendLikeDTO param) {
        //封装分页参数
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<RecommendPageVO> list = cereRecommendLikesDAO.getLikeRecommendPage(param.getTargetId(), param.getRecommendId(), param.getBlockedUserIds());
        if (list == null) {
            return new Page<>(Collections.emptyList(), 0);
        }
        list.forEach(RecommendPageVO::init);
        PageInfo<RecommendPageVO> pageInfo = new PageInfo<>(list);
        return new Page<>(pageInfo.getList(), pageInfo.getTotal());
    }

    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = {CoBusinessException.class, Exception.class})
    @Override
    public Integer commentLikesLike(RecommendLikesParam param) throws CoBusinessException {

        String currentTime = TimeUtils.yyMMddHHmmss();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("recommend_id", param.getRecommendId());
        queryWrapper.eq("user_id", param.getUserId());
        queryWrapper.eq("like_type", 2);


        CereRecommendLikes cereRecommendLikes = cereRecommendLikesDAO.selectOne(queryWrapper);
        int row;
        if (cereRecommendLikes != null) {
            row = cereRecommendLikesDAO.delete(queryWrapper);
            if (row > 0) {
                redisUtil.decrementLike(RedisEnum.USER_COMMENT_LIKE_KEY.getKey(), String.valueOf(param.getRecommendId()));
                return row;
            } else {
                throw new CoBusinessException("取消点赞失败");
            }
        }

        CereRecommendLikes likes = new CereRecommendLikes();
        likes.setRecommendId(param.getRecommendId());
        likes.setUserId(param.getUserId());
        likes.setIsRead(0);
        likes.setLikeType(2);
        likes.setCreateTime(currentTime);
        row = cereRecommendLikesDAO.insert(likes);
        if (row > 0) {
            redisUtil.incrementLike(RedisEnum.USER_COMMENT_LIKE_KEY.getKey(), String.valueOf(param.getRecommendId()));

            // 发送系统通知给原评论作者，有人点赞了评论
            Long commentPublisherId = recommendCommentDAO.getCommentPublisherId(param.getRecommendId());
            msgService.sendNotice(commentPublisherId, SysNoticeTypeEnum.LIKE.getCode(), SysNoticeTargetTypeEnum.COMMENT.getCode(),
                    String.valueOf(param.getRecommendId()), param.getUserId(), param.getUserName());

            return row;
        } else {
            throw new CoBusinessException("点赞失败");
        }

    }
}
